# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QGraphicsColorizeEffect,
    QFileDialog,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import sys
import csv
import os
import json
import subprocess
import copy
from .. import config as Config
from ..utils import Utils
from ..dlg_model_params import DlgModeResetCls
from ..params_table import ParamsTable
from .. import message_box as MBox


class DlgGenerativeModel(DlgModeResetCls):
    generativeModel_save_signal = Signal(object)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.setWindowTitle("生成模型")
        self.resize(500, 400)

        options = params.get("stages") or []

        layout = QVBoxLayout()
        self.table = ParamsTable(rows=0, columns=3)
        self.table.setHorizontalHeaderLabels(
            [
                "飞行段",
                "包含各级名称",
                "秒点",
            ]
        )
        self.table.rowSetMultiSelect([1], options={"1": options})
        self.table.rowSetFloat([2])

        self.table.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.Interactive
        )  # 第二列可手动调整
        self.table.setColumnWidth(0, 120)

        self.table.horizontalHeader().setSectionResizeMode(
            2, QHeaderView.Interactive
        )  # 第二列可手动调整
        self.table.setColumnWidth(2, 80)

        # self.table.cell_click_signal.connect(self.cell_click_signal)
        layout.addWidget(self.table)
        btnLayout = QHBoxLayout()
        importBtn = QPushButton("导入csv")
        clearBtn = QPushButton("清空")
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(importBtn)
        btnLayout.addWidget(clearBtn)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        importBtn.clicked.connect(self.on_importBtn_clicked)
        clearBtn.clicked.connect(self.on_clearBtn_clicked)
        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        # self.cacheFile = Config.cachePath + 'generativeModel.json'
        # self.loadTableData(self.cacheFile, self.table)

        data = []
        if Config.isLocation:
            self.cacheFile = Config.cachePath + "generativeModel.json"
            data = Utils.read_json(self.cacheFile)
        else:
            data = params.get("data") or []
        if not data:
            data = [
                [
                    "Stages",
                    "",
                    0.1,
                ]
            ]
        self.updataUI(data)

    def on_addBtn_clicked(self):
        self.table.addRow()

    def on_importBtn_clicked(self):
        filePath = Utils.ImportFile()
        if filePath:
            _, fileExtension = os.path.splitext(filePath)
            fileExtension = fileExtension.lower()
            if fileExtension == ".json":
                self.loadTableList(filePath, self.table)
            elif fileExtension == ".csv":
                self.load_csv(filePath)

    def on_okBtn_clicked(self):
        # self.saveTableData(self.cacheFile, self.table)
        data = self.table.getTableData()
        if (
            not data
            or len(data) == 0
            or len(data[0]) < 1
            or data[0][0] == ""
            or data[0][1] == ""
            or data[0][0] == None
            or data[0][1] == None
        ):
            MBox.warning("至少存在一条设置了 飞行段 与 包含各级名称 的数据")
            return
        if len(data) > 1:
            MBox.warning("最多仅可设置一条数据")
            return
        if Config.isLocation:
            Utils.write_json(self.cacheFile, data)
        self.close()
        self.generativeModel_save_signal.emit(data)

    def on_clearBtn_clicked(self):
        self.table.clearRow()

    def load_csv(self, filename):
        try:
            with open(
                filename, newline="", encoding="utf-8"
            ) as csvfile:  # 确保使用正确的编码
                reader = csv.reader(csvfile)
                csvData = list(reader)
                csvData = [row for row in csvData if row]
                # 如果第一行是对应的表头则删除
                del csvData[0]
                copyCsvData = csvData.copy()
                tableDict = self.table.getTableDict()
                for addIndex in range(len(copyCsvData) - 1, -1, -1):  # 倒序遍历
                    csvRow = copyCsvData[addIndex]
                    if csvRow[0] is not None and str(csvRow[0]) in tableDict:
                        self.table.updateRowData(
                            tableDict[str(csvRow[0])]["row"], csvRow
                        )
                        del csvData[addIndex]
                self.table.addMulitRows(csvData)
        except FileNotFoundError:
            print(f"Error: 文件 '{filename}' 未找到.")

    # def cell_click_signal(self, row, column):
    #     self.dlg = DlgBundledConnectingRods.show(self)

    def saveTableData(self, file, table):
        data = table.getTableData()
        Utils.write_json(file, data)

    def updataUI(self, data):
        if data:
            for row_data in data:
                self.table.addRow(rowData=row_data)

    def loadTableList(self, file, table):
        data = Utils.read_json(file)
        for row_data in data:
            table.addRow(rowData=row_data)


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = GenerativeModelDialog()
#     window.show()
#     sys.exit(app.exec_())
